package com.yzc.mihuyou.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.java.emoji.EmojiConverter;
import com.yzc.mihuyou.entity.*;
import com.yzc.mihuyou.mapper.*;
import com.yzc.mihuyou.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzc.mihuyou.util.CommentUtils;
import com.yzc.mihuyou.util.ExcelUtil;
import com.yzc.mihuyou.vo.JsonResult;
import com.yzc.mihuyou.vo.Person;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.javassist.expr.Instanceof;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Target;
import java.time.Year;
import java.util.*;
import java.util.stream.IntStream;

/**
 * <p>
 * 帖子表 	 服务实现类
 * </p>
 *
 * @author 易紫诚
 * @since 2022-04-28
 */
@Service
public class InvitationServiceImpl extends ServiceImpl<InvitationMapper, Invitation> implements InvitationService {
    @Autowired
    InvitationMapper invitationMapper;
    @Autowired
    PlateMapper plateMapper;
    @Autowired
    TopicMapper topicMapper;
    @Autowired
    IngvseService ingvseService;
    @Autowired
    UserService userService;
    @Autowired
    GiveMapper giveMapper;
    @Autowired
    TopicService topicService;
    @Autowired
    CommentService commentService;
    @Autowired
    IccompMapper iccompMapper;
    @Autowired
    AttentionService attentionService;
    @Autowired
    HomesMapper homesMapper;
    @Autowired
    CompilationsMapper compilationsMapper;

    /**
     * 导入话题
     *
     * @param file
     */
    public Map<String, Object> importProfession(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
// 获取文件的名称
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
// 获取文件的后缀名
        String pattern = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(pattern);
        List<List<String>> listContent = new ArrayList<>();
        String message = "导入成功";
        try {
            if (file != null) {
                //文件类型判断
                if (!ExcelUtil.isEXCEL(file)) {
                    message = "该文件不是excel文件";
                } else {
                    listContent = ExcelUtil.readExcelContents(file, pattern, 4);
                    //文件内容判断
                    if (listContent.isEmpty()) {
                        message = "表格内容为空";
                    } else {
                        // 循环遍历
                        for (int i = 0; i < listContent.size(); i++) {
                            Ingvse ingvse = new Ingvse();
                            Invitation invitation = new Invitation();
                            invitation.setInvitationHeadline(listContent.get(i).get(0));
                            QueryWrapper<Plate> queryWrapper=new QueryWrapper<>();
                            queryWrapper.eq("plate_name",listContent.get(i).get(1));
                            List<Plate> list2 = plateMapper.selectList(queryWrapper);
                            if (list2 != null) {
                                invitation.setGmtPlate(list2.get(0).getPlateId());
                            }

                            invitation.setInvitationCome(1L);
                            invitation.setGmtContent(listContent.get(i).get(2));
                            JSONArray array = JSONArray.fromObject(listContent.get(i).get(3));

                            try {
                                invitationMapper.insert(invitation);
                                Homes homes=new Homes();
                                homes.setConsult(3);
                                homes.setInvitaionId(invitation.getInvitationId());
                                homesMapper.insert(homes);
                                ingvse.setInvitionId(invitation.getInvitationId());
                                String uw="";
                                for (int q = 0; q < array.size(); q++) {
                                    JSONObject jsonObject = array.getJSONObject(q);
                                    Person obj = ((Person) JSONObject.toBean(jsonObject, Person.class));
                                    for (int p = 0; p < obj.name.length; p++) {
                                        QueryWrapper<Topic> wrapper = new QueryWrapper<>();
                                        wrapper.eq("topic_come", obj.name[p]);
                                        Topic topic = topicMapper.selectOne(wrapper);
                                        if (topic != null) {
                                            uw=uw+","+topic.getTopicId();
                                        } else {
                                            Topic topic1 = new Topic();
                                            topic1.setTopicImg(obj.imga[p]);
                                            topic1.setTopicCome(obj.name[p]);
                                            topicMapper.insert(topic1);
                                            uw=uw+","+topic1.getTopicId();
                                        }
                                    }
                                }
                                ingvse.setTopicId(uw);
                                ingvseService.addTope(ingvse);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            } else {
                message = "未选择文件";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code", 200);
        map.put("msg", message);
        map.put("data", fileName);
        return map;
    }


    @Override
    public JsonResult serInver(int id, int type, Long uid,PageWuer pageWuer) {
        Page<Invitation> page = new Page<>(new Long(pageWuer.getCurrent()), new Long(pageWuer.getSize()));
        QueryWrapper<Invitation> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        List<Invitation> invitationsList = null;
        System.out.println(pageWuer);
        if(pageWuer.getPerv()==null){
            if(id==0){
                wrapper.orderByDesc("gmt_dian");
                invitationsList = invitationMapper.selectPage(page, wrapper).getRecords();
            }else if(id==6){
                QueryWrapper<Invitation> queryWrappersRu=new QueryWrapper<>();
                queryWrappersRu.eq("a.consult",type+1);
                queryWrappersRu.apply("a.invitaion_id=b.invitation_id");
                invitationsList=homesMapper.rower(page,queryWrappersRu);
            } else {
                if (type!=0) {
                    if (type == 2) {
                        wrapper.eq("gmt_plate", id);
                        //  获取最新帖子
                        wrapper.orderByDesc("gmt_create");
                        invitationsList = invitationMapper.selectPage(page, wrapper).getRecords();
                        for (int l = 0; l < invitationsList.size(); l++) {
                            QueryWrapper<Invitation> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("invitation_id", invitationsList.get(l).getInvitationId());
                            Invitation invitation = invitationMapper.rowes(queryWrapper);
                            if (invitation != null) {
                                invitationsList.get(l).setZwu(invitation.getZwu());
                                invitationsList.get(l).setSums(invitation.getSums());
                            }
                        }
                    } else {
//            最新评论的表
                        wrapper.eq("b.gmt_plate", id);
                        wrapper.apply("a.blog_id=b.invitation_id");
                        wrapper.orderByDesc("a.commentNum");
                        invitationsList = invitationMapper.rower(page, wrapper);
                    }
                } else {
                    wrapper.eq("gmt_plate", id);
//            获取热门
                    wrapper.orderByDesc("gmt_dian");
                    invitationsList = invitationMapper.selectPage(page, wrapper).getRecords();
                }
            }
        }else {
            wrapper.orderByDesc("gmt_create");
            wrapper.like("invitation_headline",pageWuer.getPerv());
            invitationsList = invitationMapper.selectPage(page, wrapper).getRecords();
        }

        List list = new ArrayList<>(); //获取发帖的用户信息
        for (int i = 0; i < invitationsList.size(); i++){
            Map<String, Object> map1 = new HashMap<>();
            Document doc = Jsoup.parse(invitationsList.get(i).getGmtContent());
//           如果是首页的话就回去帖子的模块
            map1.put("plate",plateMapper.selectById(invitationsList.get(i).getGmtReprint()));
//            处理帖子内容
            Elements element = doc.getElementsByTag("p");
            Elements element2 = doc.getElementsByTag("img");
            element2.attr("preview","imgPreview");
            List<String> listImgs=new ArrayList<>();
            for (int op=0;op<element2.size();op++){
                listImgs.add(op,element2.get(op).attr("src"));
            }
            map1.put("img",listImgs);
            map1.put("text",element.text());
//            创建帖子的用户
            map1.put("nvitationsUser", userService.selUser(invitationsList.get(i).getInvitationCome()));
            //        获取点赞的数量
            QueryWrapper queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("invitation_id",invitationsList.get(i).getInvitationId());
            queryWrapper2.eq("invtation_prin",1);
            invitationsList.get(i).setSums(giveMapper.selectCount(queryWrapper2));

            //获取收藏的数量
            QueryWrapper queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("invitation_id", invitationsList.get(i).getInvitationId());
            queryWrapper3.eq("invtation_ore", 1);
            invitationsList.get(i).setZwu(giveMapper.selectCount(queryWrapper3));

//            获取帖子的话题
            Ingvse ingvse= ingvseService.selTope(invitationsList.get(i).getInvitationId());
            if(ingvse.getInvitionId()!=null && !ingvse.getTopicId().equals("")){
                List<String> ingvseList= CommentUtils.strUwe(ingvse.getTopicId());
                List<Topic> list1 = new ArrayList<>();
                for (int ik=0;ik<ingvseList.size();ik++){
                    if(!ingvseList.get(ik).equals("")){
                        list1.add(list1.size(),topicService.selTope(Integer.parseInt(ingvseList.get(ik))));
                    }
                }
                map1.put("tope", list1);

            }else {
                map1.put("tope", null);
            }
//           获取评论数量
            if (Integer.valueOf(type) != 1) {
                QueryWrapper<Invitation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("giv_we",0);
                queryWrapper.eq("blog_id", invitationsList.get(i).getInvitationId());
                invitationsList.get(i).setCommentNum(invitationMapper.rowesNun(queryWrapper).getCommentNum());
            }
//          是否收藏 是否点赞
            if (uid > 0) {
                QueryWrapper<Give> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .eq("invitation_id", invitationsList.get(i).getInvitationId())
                        .eq("give_userid", uid);
                Give give = giveMapper.selectOne(queryWrapper);
                map1.put("igact", give);
//                是否关注
                if(!invitationsList.get(i).getInvitationCome().equals(uid)){
                    Attention attention=new Attention();
                    attention.setUid(uid);
                    attention.setAid(invitationsList.get(i).getInvitationCome());
                    map1.put("attention",attentionService.relation(attention));
                }else {
                    map1.put("attention",null);
                }
            }
            //           帖子
            map1.put("nvitations", invitationsList.get(i));
            list.add(i, map1);
        }
        map.put("InveArr", list);
        PageWuer pages=new PageWuer(page.getTotal(),page.getSize(),page.getCurrent(),page.getPages());
        map.put("sizeArr", pages);
        return new JsonResult(200, "查询成功", map);
    }

    @Override
    public Map<String, Object> serOne(int id, Long uid) {
        Map<String,Object> map=new HashMap<>();
        Invitation invitation=invitationMapper.selectById(id);
        if(invitation==null){
            return  null;
        }
        invitation.setGmtDian(invitation.getGmtDian()+1);
        invitationMapper.updateById(invitation);
//        帖子
        map.put("nvitations",invitation);
//        帖子的用户
        map.put("nvitationsUser", userService.selUser(invitation.getInvitationCome()));
//        帖子的话题
        Ingvse ingvse= ingvseService.selTope(invitation.getInvitationId());
        if(ingvse.getInvitionId()!=null && !ingvse.getTopicId().equals("")){
            List<String> ingvseList= CommentUtils.strUwe(ingvse.getTopicId());
            List<Topic> list1 = new ArrayList<>();
            for (int ik=0;ik<ingvseList.size();ik++){
                list1.add(ik,topicService.selTope(Integer.parseInt(ingvseList.get(ik))));
            }
            map.put("tope", list1);
        }else {
            map.put("tope", null);
        }

//        帖子的板块
        map.put("powq",plateMapper.selectById(invitation.getGmtPlate()));

//        帖子的集合
        QueryWrapper<Iccomp> queryWrapperr=new QueryWrapper<>();
        queryWrapperr.eq("ivitaticon",invitation.getInvitationId());
        Iccomp iccomp= iccompMapper.selectOne(queryWrapperr);

        if(iccomp!=null){
            Map<String,Object> map1=new HashMap<>();
            QueryWrapper<Iccomp> queryWrapperr2=new QueryWrapper<>();
            queryWrapperr2.eq("comments_id",iccomp.getCommentsId());
            List<Iccomp> iccompList=iccompMapper.selectList(queryWrapperr2);
            map1.put("size",iccompList.size());
            map1.put("iccom",iccompList);
            int s=0;
            for (int isw=0;isw<iccompList.size();isw++){
                if(iccompList.get(isw).getCommentsId().equals(invitation.getInvitationId())){
                    s=isw;
                }
            }
            map1.put("cewn",compilationsMapper.selectById(iccomp.getCommentsId()));
            map1.put("tres",s);
            map.put("Come",map1);
        }
        map.put("plate",plateMapper.selectById(invitation.getGmtReprint()));
//        获取评论数量
        QueryWrapper<Invitation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("blog_id", invitation.getInvitationId());
        invitation.setCommentNum(invitationMapper.rowesNun(queryWrapper).getCommentNum());
        //        获取点赞的数量
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("invitation_id", invitation.getInvitationId());
        queryWrapper2.eq("invtation_prin",1);
        invitation.setSums(giveMapper.selectCount(queryWrapper2));
        //         获取收藏的数量
        QueryWrapper queryWrapper3 = new QueryWrapper();
        queryWrapper3.eq("invitation_id", invitation.getInvitationId());
        queryWrapper3.eq("invtation_ore", 1);
        invitation.setZwu(giveMapper.selectCount(queryWrapper3));
//              是否关注 是否点赞
        if (uid > 0) {
            QueryWrapper<Give> queryWrappers = new QueryWrapper<>();
            queryWrappers
                    .eq("invitation_id", invitation.getInvitationId())
                    .eq("give_userid", uid);
            Give give = giveMapper.selectOne(queryWrappers);
            map.put("igact", give);
            if(!invitation.getInvitationCome().equals(uid)){
                Attention attention=new Attention();
                attention.setUid(uid);
                attention.setAid(invitation.getInvitationCome());
                map.put("attention",attentionService.relation(attention));
            }else {
                map.put("attention",null);
            }
        }
        return map;
    }

    @Override
    public int addInse(Invitation invitation) {
        invitationMapper.insert(invitation);
        return invitation.getInvitationId();
    }

    @Override
    public int upInse(Invitation invitation) {
        int i=invitationMapper.updateById(invitation);
        return i;
    }

    @Override
    public int delInse(int id) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("invitation_id",id);
        return invitationMapper.delete(queryWrapper);
    }

    @Override
    public JsonResult suePre(int id, Long uid, PageWuer pageWuer,Date teu) {
        Map<String, Object> map = new HashMap<>();
        Page<Invitation> page = new Page<>(new Long(pageWuer.getCurrent()), new Long(pageWuer.getSize()));
        QueryWrapper<Invitation> wrapper = new QueryWrapper<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(teu);
        int mo=Integer.valueOf(calendar.get(Calendar.MONTH))+1;
        System.out.println(id);
        wrapper.apply("YEAR(gmt_create)="+calendar.get(Calendar.YEAR)+" and month(gmt_create)="+mo);
        wrapper.eq("gmt_plate", id);
        wrapper.orderByDesc("gmt_dian");
        List<Invitation> invitationsList =invitationMapper.selectPage(page,wrapper).getRecords();
        List list = new ArrayList<>(); //获取发帖的用户信息
        for (int i = 0; i < invitationsList.size(); i++){
            Map<String, Object> map1 = new HashMap<>();
//           帖子
            map1.put("nvitations", invitationsList.get(i));
            Document doc = Jsoup.parse(invitationsList.get(i).getGmtContent());
//           如果是首页的话就回去帖子的模块
            if(id==0){
                map1.put("plate",plateMapper.selectById(invitationsList.get(i).getGmtReprint()));
            }
//            处理帖子内容
            Elements element = doc.getElementsByTag("p");
            Elements element2 = doc.getElementsByTag("img");
            element2.attr("preview","imgPreview");
            List<String> listImgs=new ArrayList<>();
            for (int op=0;op<element2.size();op++){
                listImgs.add(op,element2.get(op).attr("src"));
            }
            map1.put("img",listImgs);
            map1.put("text",element.text());
//            创建帖子的用户
            map1.put("nvitationsUser", userService.selUser(invitationsList.get(i).getInvitationCome()));
            //        获取点赞的数量
            QueryWrapper queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("invitation_id", invitationsList.get(i).getInvitationId());
            queryWrapper2.eq("invtation_prin",1);
            invitationsList.get(i).setSums(giveMapper.selectCount(queryWrapper2));
            //获取关注的数量
            QueryWrapper queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("invitation_id", invitationsList.get(i).getInvitationId());
            queryWrapper3.eq("invtation_ore", 1);
            invitationsList.get(i).setZwu(giveMapper.selectCount(queryWrapper3));
//            获取帖子的话题
            Ingvse ingvse= ingvseService.selTope(invitationsList.get(i).getInvitationId());
            if(ingvse.getInvitionId()!=null && !ingvse.getTopicId().equals("")){
                List<String> ingvseList= CommentUtils.strUwe(ingvse.getTopicId());
                List<Topic> list1 = new ArrayList<>();
                for (int ik=0;ik<ingvseList.size();ik++){
                    list1.add(ik,topicService.selTope(Integer.parseInt(ingvseList.get(ik))));
                }
                map.put("tope", list1);
            }else {
                map.put("tope", null);
            }

//           获取评论数量
            QueryWrapper<Invitation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("giv_we",0);
            queryWrapper.eq("blog_id", invitationsList.get(i).getInvitationId());
            invitationsList.get(i).setCommentNum(invitationMapper.rowesNun(queryWrapper).getCommentNum());

//          是否收藏 是否点赞
            if (uid > 0) {
                QueryWrapper<Give> queryWrappers = new QueryWrapper<>();
                queryWrappers
                        .eq("invitation_id", invitationsList.get(i).getInvitationId())
                        .eq("give_userid", uid);
                Give give = giveMapper.selectOne(queryWrappers);
                map1.put("igact", give);
//                是否关注
                if(!invitationsList.get(i).getInvitationCome().equals(uid)){
                    Attention attention=new Attention();
                    attention.setUid(uid);
                    attention.setAid(invitationsList.get(i).getInvitationCome());
                    map1.put("attention",attentionService.relation(attention));
                }else {
                    map1.put("attention",null);
                }
            }
            list.add(i, map1);
        }
        map.put("InveArr", list);
        PageWuer pages=new PageWuer(page.getTotal(),page.getSize(),page.getCurrent(),page.getPages());
        map.put("sizeArr", pages);
        return new JsonResult(200, "查询成功", map);
    }

    @Override
    public Map<String, Object> sow(int id, String type, Long uid) {
        Map<String,Object> map=new HashMap<>();
        Compilations compilations= compilationsMapper.selectById(id);
        map.put("comei",compilations);
        compilations.setGmtDian(compilations.getGmtDian()+1);
        compilationsMapper.updateById(compilations);

        QueryWrapper<Iccomp> icoom=new QueryWrapper<>();
        icoom.eq("comments_id",compilations.getId());

        if(type.equals("0")){
            System.out.println(type);
            icoom.orderByDesc("gmt_create");
        }else if(type.equals("1")){
            System.out.println(type);
            icoom.orderByAsc("gmt_create");
        }

        List<Iccomp> iccomp=iccompMapper.selectList(icoom);


        List<Invitation> invitationsList=new ArrayList<>();

        for (Iccomp iccomp1:iccomp){
            invitationsList.add(invitationsList.size(),invitationMapper.selectById(iccomp1.getIvitaticon()));
        }

        List list = new ArrayList<>(); //获取发帖的用户信息
        for (int i = 0; i < invitationsList.size(); i++){
            Map<String, Object> map1 = new HashMap<>();
            Document doc = Jsoup.parse(invitationsList.get(i).getGmtContent());
//           如果是首页的话就回去帖子的模块
            map1.put("plate",plateMapper.selectById(invitationsList.get(i).getGmtReprint()));
//            处理帖子内容
            Elements element = doc.getElementsByTag("p");
            Elements element2 = doc.getElementsByTag("img");
            element2.attr("preview","imgPreview");
            List<String> listImgs=new ArrayList<>();
            for (int op=0;op<element2.size();op++){
                listImgs.add(op,element2.get(op).attr("src"));
            }
            map1.put("img",listImgs);
            map1.put("text",element.text());
//            创建帖子的用户
            map1.put("nvitationsUser", userService.selUser(invitationsList.get(i).getInvitationCome()));
            //        获取点赞的数量
            QueryWrapper queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("invitation_id",invitationsList.get(i).getInvitationId());
            queryWrapper2.eq("invtation_prin",1);
            invitationsList.get(i).setSums(giveMapper.selectCount(queryWrapper2));

            //获取收藏的数量
            QueryWrapper queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("invitation_id", invitationsList.get(i).getInvitationId());
            queryWrapper3.eq("invtation_ore", 1);
            invitationsList.get(i).setZwu(giveMapper.selectCount(queryWrapper3));

//            获取帖子的话题
            Ingvse ingvse= ingvseService.selTope(invitationsList.get(i).getInvitationId());
            if(ingvse.getInvitionId()!=null && !ingvse.getTopicId().equals("")){
                List<String> ingvseList= CommentUtils.strUwe(ingvse.getTopicId());
                List<Topic> list1 = new ArrayList<>();
                for (int ik=0;ik<ingvseList.size();ik++){
                    if(!ingvseList.get(ik).equals("")){
                        list1.add(list1.size(),topicService.selTope(Integer.parseInt(ingvseList.get(ik))));
                    }
                }
                map1.put("tope", list1);

            }else {
                map1.put("tope", null);
            }
//           获取评论数量
            if (Integer.valueOf(type) != 1) {
                QueryWrapper<Invitation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("giv_we",0);
                queryWrapper.eq("blog_id", invitationsList.get(i).getInvitationId());
                invitationsList.get(i).setCommentNum(invitationMapper.rowesNun(queryWrapper).getCommentNum());
            }
//          是否收藏 是否点赞
            if (uid > 0) {
                QueryWrapper<Give> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .eq("invitation_id", invitationsList.get(i).getInvitationId())
                        .eq("give_userid", uid);
                Give give = giveMapper.selectOne(queryWrapper);
                map1.put("igact", give);
//                是否关注
                if(!invitationsList.get(i).getInvitationCome().equals(uid)){
                    Attention attention=new Attention();
                    attention.setUid(uid);
                    attention.setAid(invitationsList.get(i).getInvitationCome());
                    map1.put("attention",attentionService.relation(attention));
                }else {
                    map1.put("attention",null);
                }
            }
            //           帖子
            map1.put("nvitations", invitationsList.get(i));
            list.add(i, map1);
        }
        map.put("InveArr", list);
        return map;
    }


}
